package inits

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"srv-server/basic/config"
	"srv-server/basic/global"
)

func InitAll() {

	NacosInit()
	MysqlInit()
	RedisInit()
}

func RedisInit() {
	data := global.Conf.Redis
	global.Rdb = redis.NewClient(&redis.Options{
		Addr:     data.Addr,
		Password: data.Pass, // no password set
		DB:       data.DB,   // use default DB
	})
	result, err := global.Rdb.Ping(context.Background()).Result()
	log.Println(result)
	if err != nil {
		panic(err)
	}
}

func NacosInit() {
	clientConfig := constant.ClientConfig{
		NamespaceId:         config.NacosConf.NamespaceId, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      config.NacosConf.IpAddr,
			ContextPath: "/nacos",
			Port:        config.NacosConf.Port,
			Scheme:      "http",
		},
	}
	configClient, _ := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	content, _ := configClient.GetConfig(vo.ConfigParam{
		DataId: config.NacosConf.DataId,
		Group:  config.NacosConf.Group})
	app := global.Conf
	json.Unmarshal([]byte(content), &app)
	global.Conf = app
	fmt.Println(global.Conf)
	log.Println("nacos success")
}
func MysqlInit() {
	var err error
	data := global.Conf.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", data.User, data.Pass, data.Host, data.Port, data.Data)
	//dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		panic("数据库连接失败")
	} else {
		log.Println("数据库连接成功")
	}
}
